﻿using NLog;
using ZMQ;
using System.Text;
using System.Threading;
using System.Configuration;
using System.ServiceProcess;

namespace BidNotifier
{
    public class BidNotifyService : ServiceBase
    {
        private Thread workerThread;
        private readonly Logger logger;
        private readonly string serviceName;
        private readonly string publisherEndpoint;
        private readonly string subscriberEndpoint;
        public BidNotifyService()
        {
            serviceName = ConfigurationManager.AppSettings["serviceName"] ?? "BidNotifyService";
            publisherEndpoint = ConfigurationManager.AppSettings["publisherEndpoint"] ?? "tcp://127.0.0.1:5555";
            subscriberEndpoint = ConfigurationManager.AppSettings["subscriberEndpoint"] ?? "tcp://127.0.0.1:5000";
            logger = LogManager.GetCurrentClassLogger();
            ServiceName = serviceName;
            CanPauseAndContinue = false;
            AutoLog = false;
        }

        protected override void OnStart(string[] args)
        {
            if ((workerThread == null) || ((workerThread.ThreadState & (ThreadState.Unstarted | ThreadState.Stopped)) != 0))
            {
                workerThread = new Thread(ZeroMq) { IsBackground = true, Priority = ThreadPriority.AboveNormal };
                workerThread.Start();
            }
            logger.Info("OnStart");
        }

        protected override void OnStop()
        {
            if ((workerThread != null) && (workerThread.IsAlive))
            {
                workerThread.Abort();
                workerThread = null;
            }
            logger.Info("OnStop");
            ExitCode = 0;
        }

        private void ZeroMq()
        {
            try
            {
                using (var context = new Context(1))
                using (Socket subscriber = context.Socket(SocketType.SUB), publisher = context.Socket(SocketType.PUB))
                {
                    publisher.Bind(publisherEndpoint);
                    subscriber.Connect(subscriberEndpoint);
                    subscriber.Subscribe(string.Empty, Encoding.UTF8);

                    while (true)
                    {
                        var data = subscriber.Recv(Encoding.UTF8);
                        publisher.Send(data, Encoding.UTF8);
                    }
                }
            }
            catch (ZMQ.Exception e)
            {
                logger.Error(e.Message);
            }
        }
    }
}
